package la.common.xml;

import java.io.OutputStream;
import java.io.StringWriter;
import java.io.Writer;

import javax.xml.transform.OutputKeys;
import javax.xml.transform.Result;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import la.common.CommonException;

import org.w3c.dom.Document;
import org.w3c.dom.Node;

import com.sun.org.apache.xml.internal.serialize.OutputFormat;
import com.sun.org.apache.xml.internal.serialize.XMLSerializer;

public class Node2String {
	public static String node2String(Node node) throws CommonException {
		try {
			TransformerFactory tf = javax.xml.transform.TransformerFactory.newInstance();
//			tf.setAttribute("indent-number", 2);
			Transformer tranfer = tf.newTransformer();
			Writer writer = new StringWriter();
			Result r = new StreamResult( writer ); 
			tranfer.transform( new DOMSource( node ), r );
            //Setup indenting to "pretty print"
			tranfer.setOutputProperty(OutputKeys.INDENT, "yes");
			tranfer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
			return writer.toString();
			
		} catch ( RuntimeException e ) {
			throw e;
		} catch (Exception e) {
			throw new CommonException( e );
		}
	}
	
	public static String node2String(Document doc) throws CommonException {
		try {
			return serialize( doc );
		} catch ( RuntimeException e ) {
			throw e;
		} catch (Exception e) {
			throw new CommonException( e );
		}
	}

	public static String serialize(Document doc) throws Exception {
        OutputFormat format = new OutputFormat(doc);
        format.setLineWidth(65);
        format.setIndenting(true);
        format.setIndent(2);
        StringWriter w = new StringWriter();
        XMLSerializer serializer = new XMLSerializer(w, format);
        serializer.serialize(doc);
        return w.toString();
    }
	
}
